package com.api.signature.auto.spring;

import com.api.signature.auto.config.ApiSignConfig;
import com.api.signature.auto.dao.ApiSignDao;
import com.api.signature.auto.dao.ApiSignDaoDefaultImpl;
import com.api.signature.auto.service.ApiSignService;
import com.api.signature.auto.service.impl.ApiSignServiceDefaultImpl;
import com.api.signature.auto.util.ServerSignUtil;
import com.signature.auto.common.util.ApiFoxUtil;
import com.signature.auto.common.util.SignUtil;

/**
 * @author Jerry
 * @date 2024-01-24 11:07
 * 管理 api签名 所有全局组件，可通过此类快速获取、写入各种全局组件对象
 */
public class ApiSignContext {

    /**
     * 全局配置对象
     */
    public volatile static ApiSignConfig apiSignatureConfig;

    public static void setConfig(ApiSignConfig config) {
        setConfigMethod(config);
        // 打印 banner
        if (config != null && config.getIsPrint()) {
            ApiFoxUtil.printApiSignature();
        }
    }

    private static void setConfigMethod(ApiSignConfig config) {
        ApiSignContext.apiSignatureConfig = config;
    }

    /**
     * 获取 ApiSignatureConfig 的全局配置信息
     *
     * @return 全局配置信息
     */
    public static ApiSignConfig getConfig() {
        if (apiSignatureConfig == null) {
            synchronized (ApiSignContext.class) {
                if (apiSignatureConfig == null) {
                    // TODO 默认创建方式
                }
            }
        }
        return apiSignatureConfig;
    }

    private volatile static ServerSignUtil signUtil;

    public static SignUtil getSignUtil() {
        if (signUtil == null) {
            synchronized (ApiSignContext.class) {
                if (signUtil == null) {
                    signUtil = new ServerSignUtil();
                }
            }
        }
        return signUtil;
    }


    private volatile static ApiSignDao apiSignDao;

    public static void setApiSignDao(ApiSignDao apiSignDao) {
        setApiSignDaoMethod(apiSignDao);
    }

    private static void setApiSignDaoMethod(ApiSignDao apiSignDao) {
        // 用户自己注入的
        if (apiSignDao != null) {
            ApiSignContext.apiSignDao = apiSignDao;
        }
    }

    public static ApiSignDao getApiSignDao() {
        if (apiSignDao == null) {
            synchronized (ApiSignContext.class) {
                if (apiSignDao == null) {
                    setApiSignDaoMethod(new ApiSignDaoDefaultImpl());
                }
            }
        }
        return apiSignDao;
    }

    private volatile static ApiSignService apiSignService;

    public static void setApiSignService(ApiSignService apiSignService) {
        ApiSignContext.apiSignService = apiSignService;
    }

    public static ApiSignService getApiSignService() {
        if (apiSignService == null) {
            synchronized (ApiSignContext.class) {
                if (apiSignService == null) {
                    setApiSignService(new ApiSignServiceDefaultImpl());
                }
            }
        }
        return apiSignService;
    }
}
